package cn.xxstudy.blog.controller.admin

import cn.xxstudy.blog.bean.Msg
import cn.xxstudy.blog.entity.Category
import cn.xxstudy.blog.service.CategoryService
import org.slf4j.LoggerFactory
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.data.domain.Pageable
import org.springframework.data.domain.Sort
import org.springframework.data.web.PageableDefault
import org.springframework.stereotype.Controller
import org.springframework.ui.Model
import org.springframework.validation.BindingResult
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.PathVariable
import org.springframework.web.bind.annotation.PostMapping
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.servlet.mvc.support.RedirectAttributes
import javax.validation.Valid

/**
 * 作者：wuxinxi on 2020/11/25
 * 包名：cn.xxstudy.blog.controller.admin
 * TODO:分类管理
 */
@Controller
@RequestMapping("/admin")
class ManagerCategoryController {
    private val logger=LoggerFactory.getLogger(this::class.java)
    companion object {
        private const val CATEGORY_LIST = "admin/manager-blog-category"
        private const val CATEGORY_EDIT = "admin/manager-blog-category-edit"
    }

    @Autowired
    private lateinit var categoryService: CategoryService

    /**
     * 分类-列表
     */
    @GetMapping("/category")
    fun categoryList(@PageableDefault(sort = ["id"], direction = Sort.Direction.DESC) pageable: Pageable,
                     model: Model): String {
        model.addAttribute("categoryPage", categoryService.listCategory(pageable))
        return CATEGORY_LIST
    }

    /**
     * 分类-新建
     */
    @GetMapping("/category/create")
    fun createCategory(model: Model): String {
        model.addAttribute("category", Category())
        return CATEGORY_EDIT
    }

    /**
     * 分类-新建-POST 提交
     */
    @PostMapping("/category/create")
    fun createCategoryPost(@Valid category: Category, result: BindingResult,
                           redirectAttributes: RedirectAttributes): String {
        val cg = categoryService.getCategoryByName(category.categoryName)
        if (cg != null) {
            result.rejectValue("categoryName", "categoryNameRepeat", "${category.categoryName} 类型已存在")
        }
        if (result.hasErrors()) {
            return CATEGORY_EDIT
        }
        val cgRep = categoryService.createCategory(category)
        redirectAttributes.addFlashAttribute("response", "${category.categoryName} 类型添加${if (cgRep == null) "失败" else "成功"}")
        return "redirect:/admin/category"
    }


    /**
     * 编辑
     */
    @GetMapping("/category/{id}/create")
    fun editCategory(@PathVariable id: Long, model: Model): String {
        model.addAttribute("category", categoryService.getCategoryById(id))
        return CATEGORY_EDIT
    }

    /**
     * @category 编辑后的
     * @categoryName 编辑前
     */
    @PostMapping("/category/{categoryName}")
    fun editCategoryPost(@Valid category: Category,result: BindingResult, @PathVariable categoryName: String,
                         model: Model, redirectAttributes: RedirectAttributes): String {
        val cg = categoryService.getCategoryByName(category.categoryName)
        if (cg != null) {
            result.rejectValue("categoryName", "categoryNameRepeat", "${category.categoryName} 类别已存在")
            return CATEGORY_EDIT
        }
        val success = categoryService.updateByName(categoryName, category)
        redirectAttributes.addFlashAttribute("msg",
                if (success) Msg(true, "$categoryName 修改为 ${category.categoryName}修改成功")
                else Msg(false, "$categoryName 修改为 ${category.categoryName}修改失败"))
        return "redirect:/admin/category"
    }

    //TODO 待优化：仅刷新当前页面
    @GetMapping("/category/delete/{categoryName}")
    fun delete(@PathVariable categoryName: String, redirectAttributes: RedirectAttributes): String {
        val deleteByName = categoryService.deleteByName(categoryName)
        redirectAttributes.addFlashAttribute("msg",
                if (deleteByName) Msg(true, "$categoryName 删除成功")
                else Msg(false, "$categoryName 删除失败"))
        return "redirect:/admin/category"
    }

}